package com.shiwaixiangcun.customer.module.property

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.model.HttpParams
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterFeeRecord
import com.shiwaixiangcun.customer.entity.CommonData
import com.shiwaixiangcun.customer.entity.MonthItemEntity
import com.shiwaixiangcun.customer.entity.PropertyPaymentDetailEntity
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.network.NetworkHelper
import com.shiwaixiangcun.customer.pay.AliInfo
import com.shiwaixiangcun.customer.pay.AliPay
import com.shiwaixiangcun.customer.pay.WeiXinInfo
import com.shiwaixiangcun.customer.pay.WeiXinPay
import com.shiwaixiangcun.customer.ui.dialog.PayDialog
import com.shiwaixiangcun.customer.ui.fragment.LazyFragment
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.fragment_payment_detail.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val HOUSE_ID = "houseID"

/**
 * 物业缴费详情页面
 */
class PaymentDetailFragment : LazyFragment(), View.OnClickListener {


    private var houseId: Long? = null
    private var mNetworkHelper: NetworkHelper? = null

    private var mMonthFeeList: MutableList<MonthItemEntity>? = null
    private var mAdapter: AdapterFeeRecord? = null

    private var mShouldPay: String? = ""
    private var viewHeader: View? = null

    private var mBtnPay: Button? = null
    private var mTvShouldPay: TextView? = null
    private var mTvHouseName: TextView? = null
    private var mTvPropertyName: TextView? = null
    private var mDistance = 0
    private var maxDistance: Int? = null
    private var mEntity: PropertyPaymentDetailEntity? = null

    private val payDialog = PayDialog()
    private var mItemIds: StringBuilder = StringBuilder()

    override fun onClick(v: View?) {

        when (v?.id) {
            R.id.btn_pay_now, R.id.btn_pay -> {

                pay()

            }

        }
    }

    /**
     * 支付
     */
    private fun pay() {
        val bundle = Bundle()
        val strIds = mItemIds.dropLast(1).toString()
        bundle.putString("shouldPay", mShouldPay?.let { it })
        payDialog.arguments = bundle


        payDialog.showDialog(activity?.supportFragmentManager, "payDialog")

        payDialog.setListener {
            val defaultPay = payDialog.defaultPay
            when (defaultPay) {
                PayDialog.PAY_ALI -> {
                    val httpParams = HttpParams()
                    httpParams.put("payWay", "ZhiFuBao")
                    httpParams.put("statementIds", strIds)
                    mNetworkHelper?.postRequestWithToken(GlobalApi.payPropertyZfb, true, httpParams, object : NetworkHelper.NetWorkHelperBack {
                        override fun requestSuccess(json: String) {
                            val type = object : TypeToken<ResponseEntity<AliInfo>>() {}.type
                            val entity = JsonUtil.fromJson<ResponseEntity<AliInfo>>(json, type)
                            if (null == entity || entity.data.zhiFuBaoResponse == null) {
                                Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show()
                                return
                            }
                            val zhiFuBaoResponse = entity.data.zhiFuBaoResponse
                            AliPay.instance.pay(zhiFuBaoResponse!!, mActivity)
                        }

                        override fun requestFail() {
                        }
                    })
                }

                PayDialog.PAY_WEXIN -> {
                    val httpParams = HttpParams()
                    httpParams.put("payWay", "WeiXin")
                    httpParams.put("statementIds", strIds)
                    mNetworkHelper?.postRequestWithToken(GlobalApi.payPropertyWx, true, httpParams, object : NetworkHelper.NetWorkHelperBack {
                        override fun requestSuccess(json: String) {
                            val type = object : TypeToken<ResponseEntity<WeiXinInfo>>() {

                            }.type
                            val entity = JsonUtil.fromJson<ResponseEntity<WeiXinInfo>>(json, type)
                                    ?: return
                            val weiXinResponse = entity.data.weiXinResponse
                            val wXpay = WeiXinPay(weiXinResponse!!)
                            wXpay.createWXAPI(mActivity)
                            wXpay.sendPayReq()
                        }

                        override fun requestFail() {
                        }
                    })

                }
                0 -> Toast.makeText(mContext, "请选择一种支付方式", Toast.LENGTH_SHORT).show()
                else -> {
                }
            }
        }
    }

    companion object {
        const val SUCCESS: Int = 0x0001
        @JvmStatic
        fun newInstance(param1: Long) =
                PaymentDetailFragment().apply {
                    arguments = Bundle().apply {
                        putLong(HOUSE_ID, param1)
                    }
                }
    }

    override fun getContentViewLayoutID(): Int {
        return R.layout.fragment_payment_detail
    }

    override fun initViewsAndEvents(view: View?) {

        maxDistance = 900
        mMonthFeeList = ArrayList()
        mAdapter = AdapterFeeRecord(mMonthFeeList)
        rv_detail.layoutManager = LinearLayoutManager(this.mContext)
        rv_detail.adapter = mAdapter
        initHeaderView()
        btn_pay_now.setOnClickListener(this)
        rv_detail.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                mDistance += dy
                if (mDistance >= maxDistance!!) {
                    clayout_pay.visibility = View.VISIBLE
                } else {
                    clayout_pay.visibility = View.INVISIBLE

                }
            }
        })

    }

    private fun initHeaderView() {

        viewHeader = layoutInflater.inflate(R.layout.header_payment_detial, null, false)

        mBtnPay = viewHeader?.findViewById(R.id.btn_pay)
        mTvShouldPay = viewHeader?.findViewById(R.id.tv_fee_price)
        mTvHouseName = viewHeader?.findViewById(R.id.tv_house_name)
        mTvPropertyName = viewHeader?.findViewById(R.id.tv_property_name)
        mBtnPay?.setOnClickListener(this)

    }

    override fun onFirstUserVisible() {
    }

    override fun onUserVisible() {
    }

    override fun onUserInvisible() {
    }

    override fun destroyViewAndThing() {
        EventUtil.getInstance().unregister(this)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            houseId = it.getLong(HOUSE_ID)
        }
        EventUtil.getInstance().register(this)

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
    }

    private fun initData() {
        mNetworkHelper = NetworkHelper(this.context!!, this.fragmentManager!!)
        val httpParams = HttpParams()
        houseId?.let { httpParams.put("houseId", it) }
        mNetworkHelper?.getRequestWithToken(GlobalApi.propertyFee, true, httpParams, object : NetworkHelper.NetWorkHelperBack {
            override fun requestSuccess(json: String) {
                val type = object : TypeToken<CommonData<PropertyPaymentDetailEntity>>() {}.type
                val fromJson = JsonUtil.fromJson<CommonData<PropertyPaymentDetailEntity>>(json, type)
                        ?: return
                when (fromJson.responseCode) {
                    1001 -> {
                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.PAYMENT_DETAIL, SUCCESS, fromJson.data))
                    }
                }

            }

            override fun requestFail() {
            }
        })
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {

        when (simpleEvent.mEventType) {
        //更新详细数据
            SimpleEvent.PAYMENT_DETAIL -> {
                when (simpleEvent.mEventValue) {
                    SUCCESS -> {

                        val dataEntity = simpleEvent.mData as PropertyPaymentDetailEntity
                        if (!dataEntity.isExistBill || !dataEntity.isSupport) {
                            val newInstance = OnePropertyFragment.newInstance(dataEntity)
                            val supportFragmentManager = this.activity?.supportFragmentManager
                            supportFragmentManager?.popBackStack()
                            supportFragmentManager
                                    ?.beginTransaction()
                                    ?.add(R.id.property_content, newInstance)
                                    ?.addToBackStack(null)
                                    ?.commitAllowingStateLoss()

                        } else {
                            mEntity = dataEntity
                            mShouldPay = dataEntity.unsettledAmount
                            tv_pay.text = "￥ ${dataEntity.unsettledAmount}"
                            mTvShouldPay?.text = dataEntity.unsettledAmount.toString()
                            mTvHouseName?.text = dataEntity.house
                            mTvPropertyName?.text = dataEntity.property
                            mMonthFeeList?.addAll(dataEntity.detail)
                            mAdapter?.removeAllHeaderView()
                            mAdapter?.addHeaderView(viewHeader)
                            mAdapter?.notifyDataSetChanged()
                            for (item in dataEntity.detail) {

                                mItemIds.append(item.statementId).append(",")


                            }
                        }
                    }
                }
            }
        //支付成功
            SimpleEvent.PAY_SUCCESS -> {
                Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show()
                if (payDialog.isVisible) {
                    payDialog.dismiss()
                }

                val paySuccessFragment =
                        mEntity?.let { PaySuccessFragment.newInstance(it) }

                val supportFragmentManager = this.activity?.supportFragmentManager
                supportFragmentManager?.popBackStack()

                supportFragmentManager
                        ?.beginTransaction()
                        ?.add(R.id.property_content, paySuccessFragment)
                        ?.addToBackStack(null)
                        ?.commit()


            }

        //支付失败
            SimpleEvent.PAY_FAIL -> {
                if (payDialog.isVisible) {
                    payDialog.dismiss()
                }
                Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT)
                        .show()
            }

            else -> {
                return
            }
        }
    }
}




